package cn.edu.swu.book;


import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/JsonBooks")
public class queryBookJson extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sql="select * from book";
        try{
            List<BOOK> books=bookApplication.getInstance().queryBook(sql);
            ObjectMapper objectMapper=new ObjectMapper();
            String json=objectMapper.writeValueAsString(books);
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            try(Writer writer=resp.getWriter()){
                writer.write(json);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
